package com.ff.sms.engine.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ff.sms.engine.config.Dh3tConfig;
import com.ff.sms.engine.service.Dh3tSmsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 1.0 刘风栓
 */
@Service
public class Dh3tSmsServiceImpl implements Dh3tSmsService {

    @Autowired
    private Dh3tConfig dh3tConfig;

    @Override
    public String getShortUrl(String fullUrl, Integer days) {
        String reqUrl = dh3tConfig.getShortUrl();
        if (StrUtil.isEmpty(reqUrl)) {
            return null;
        }
        JSONObject json = new JSONObject(2);
        json.put("account", dh3tConfig.getAccount());
        json.put("password", dh3tConfig.getPassword());
        json.put("url", fullUrl);
        json.put("days", days);
        String response = HttpUtil.post(reqUrl, json.toJSONString());

        // {"result":0,"desc":"提交成功","shortUrl":"dh3t.cn/UT50hv"}
        if (StringUtils.isNotBlank(response)) {
            JSONObject jsonObject = JSONObject.parseObject(response);
            if (jsonObject.containsKey("result") && jsonObject.getInteger("result").equals(0) && jsonObject.containsKey("shortUrl")) {
                String shortUrl = jsonObject.getString("shortUrl");
                if (shortUrl.indexOf("http://") == -1) {
                    shortUrl = "http://" + shortUrl;
                }
                return shortUrl;
            }
        }

        return null;
    }
}
